<?php

namespace addons\addons\controller;

use app\admin\model\addons\Lists;
use think\addons\Controller;
use app\common\controller\Backend;
use think\Loader;
use app\common\controller\Api;

class Index extends Api
{

    protected $model = null;
    protected $noNeedLogin = '*';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\addons\Lists;

    }

    public function index()
    {
        $limit = 100;
        $list = $this->model
            ->paginate($limit);

        $category = [
            [
                'id'=>'14',
                'name'=>'本插件接口仅做局域网开发测试用，不含授权认证接口，无需填写账号密码即可登录'
            ]
        ];
        $lists = $list->items();

        $row = [];
        foreach ($lists as $k => $v){
            $row[] = [
                'category_id'=>14,
                'name'=>$v['name'],
                'title'=>$v['title'],
                'intro'=>$v['intro'],
                'author'=>$v['author'],
                'require'=>'>= 1.0.0',
                'releaselist'=>[
                    [
                        'version'=>'1.0.0',
                        'require'=>'>= 1.0.0'
                    ]
                ]
            ];
        }
        $result = ["total" => $list->total(), "rows" => $row,'category'=>$category];;
        $this->resultMsg($result);
    }


    public function authorization(){
        $result = ["code" => 0, "msg" => '授权功能请通过官方API授权'];
        return $result;
    }

    public function download(){

        $name = $this->request->get('name');
        $fileUrl = $this->model->where('name',$name)->value('fileurl');
        $this->success('ok',[
            'url'=>cdnurl($fileUrl)
        ]);
    }

    function resultMsg($array)
    {
        $callback = $this->request->get('callback');
        if($callback){
            echo $callback."(".json_encode($array,JSON_UNESCAPED_UNICODE).")";
        }else{
            echo json_encode($array,JSON_UNESCAPED_UNICODE);
        }
    }

    public function userIndex()
    {
        $this->_success('ok', ['welcome' => '试用自建插件市场']);
    }
    public function login()
    {
        $account = $this->request->get("account", '麦克·伊文斯');
        $this->_success('请给时光以生命,给岁月以文明', ['id' => 1, 'username' => $account, 'nickname' => '麦克·伊文斯', 'token' => 'test']);
    }

    public function logout()
    {
        $this->_success('消灭人类暴政！世界属于三体');
    }

    function _success($msg, $data = [])
    {
        $callback = $this->request->get('callback');
        // 旧版本插件市场返回参数兼容
        if ($callback) {
            $array = [
                'code' => 1,
                'msg' => $msg,
                'data' => $data
            ];
            echo $callback . "(" . json_encode($array, JSON_UNESCAPED_UNICODE) . ")";
        } else {
            $this->success($msg, $data);
        }
    }
}
